package com.example.demoapp.bean.util;


import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.demoapp.bean.Res;
import com.example.demoapp.bean.User;
import com.example.demoapp.config.URLs;
import com.example.demoapp.vollley.MySingleton;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.jidcoo.android.widget.commentview.defaults.DefaultCommentModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

public class JSONParser {

    public static Res parseJson(String json) {
        try{
            JSONObject jsonObject = new JSONObject(json);
            Res res = new Res();
            res.setCode(jsonObject.getInt("code"));
            res.setMessage(jsonObject.getString("msg"));
            res.setData(jsonObject.get("data"));
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static User parseUserJson(String json) {
        try{
            JSONObject jsonObject = new JSONObject(json);
            JSONObject usr = new JSONObject(jsonObject.getString("user"));
            final Gson gson = new Gson();
            User user = gson.fromJson(usr.toString(), User.class);
            user.setToken(jsonObject.getString("token"));
            return user;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static DefaultCommentModel getConmment(JSONArray dataArray, final Context context,String token){
        DefaultCommentModel DefaultCommentModel = new DefaultCommentModel();
        ArrayList<DefaultCommentModel.Comment> commentList = new ArrayList<DefaultCommentModel.Comment>();
        try {
            for (int i = 0; i < dataArray.length(); i++) {
                final int index = i;
                JSONObject jsonDetailInfo = dataArray.getJSONObject(i);
                JSONObject sender = jsonDetailInfo.getJSONObject("sender");
                DefaultCommentModel.Comment comment = new DefaultCommentModel.Comment();
                comment.setId(jsonDetailInfo.getLong("id"));
                comment.setPosterName(sender.getString("nickName"));
                comment.setFid(jsonDetailInfo.getLong("id"));
                comment.setComment(jsonDetailInfo.getString("content"));
                Timestamp ts = Timestamp.valueOf(jsonDetailInfo.getString("createTime"));
                comment.setDate(ts.getTime());
                comment.setPrizes(jsonDetailInfo.getInt("agree"));
                comment.setPid(0);
                commentList.add(comment);
            }

            final ArrayList<DefaultCommentModel.Comment> updatedList = new ArrayList<>();
//            final CountDownLatch latch = new CountDownLatch(commentList.size());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (final DefaultCommentModel.Comment comment : commentList) {
                        Log.d("遍历commentList", comment.toString());
                        sendRequest(context,token, comment.id, new RequestCallback() {
                            @Override
                            public void onSuccess(ArrayList<DefaultCommentModel.Comment.Reply> response) {
                                Log.d("进入success", response.toString());
                                // 在请求成功的回调中将数据存储在对象中
                                comment.setReplies(response);

                                // 将已更新的对象添加到新的列表中
                                synchronized (updatedList) {
                                    updatedList.add(comment);

                                    // 检查是否已迭代完整个列表
                                    if (updatedList.size() == commentList.size()) {
                                        // 迭代完成后，返回包含所有对象的更新列表
                                        // 这里可以执行其他逻辑操作
                                        Log.d("updatedList", updatedList.toString());
                                    }
                                }
//                                latch.countDown();
                            }

                            @Override
                            public void onError(VolleyError error) {
                                // 处理请求错误
                                Log.d("onError", error.toString());
//                                latch.countDown();
                            }
                        });
                    }
                }
            }).start();
            DefaultCommentModel.setComments(commentList);
            DefaultCommentModel.setCurrentPage(1);
            DefaultCommentModel.setNextPage(2);
            DefaultCommentModel.setPageSize(2);    // 每一页数据量
            DefaultCommentModel.setPrefPage(0);     // 上一页
            DefaultCommentModel.setTotalDataSize(2);
            DefaultCommentModel.setTotalPages(1);
                    } catch (JSONException e) {
            return null;
        }

        return DefaultCommentModel;
    }


    public interface RequestCallback {
        void onSuccess(ArrayList<DefaultCommentModel.Comment.Reply> response);
        void onError(VolleyError error);
    }

    public static void sendRequest(Context context, String token, Long commentid, final RequestCallback callback) {
        // 创建请求URL，这里假设根据属性值property构建URL
        Log.d("发起请求", String.valueOf(commentid));
        // 创建请求对象
        HashMap map = new HashMap();
        map.put("commentId","1686037921580326913");
        map.put("page",0);
        map.put("pageSize", 10);
        ArrayList<DefaultCommentModel.Comment.Reply> replylist = new ArrayList<>();
        JsonObjectRequest request = new JsonObjectRequest(URLs.reply_list, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        Log.d("rep请求返回", response.toString());
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {

                                JSONObject jdata = jsonObject.getJSONObject("data");
                                // 从JSONObject中获取"data"字段对应的JSONArray
                                JSONArray dataArray = jdata.getJSONArray("records");
                                for (int j = 0; j < dataArray.length(); j++) {
                                    JSONObject dataObject = dataArray.getJSONObject(j);
                                    DefaultCommentModel.Comment.Reply reply = new DefaultCommentModel.Comment.Reply();
                                    reply.setReply(dataObject.getString("content"));
                                    Timestamp ts = Timestamp.valueOf(dataObject.getString("createTime"));
                                    reply.setDate(ts.getTime());
                                    reply.setId(dataObject.getLong("id"));
                                    reply.setPid(0);
                                    reply.setPrizes(dataObject.getInt("agree"));
                                    reply.setKid(commentid);
                                    JSONObject fromUser = dataObject.getJSONObject("fromUser");
                                    reply.setReplierName(fromUser.getString("nickName"));
                                    replylist.add(reply);
                                    Log.d("reply", reply.toString());
                                }
                                callback.onSuccess(replylist);


                            }
                        } catch (Exception e) {
                            callback.onError(new VolleyError(e.getMessage()));
                            Log.i("reply出现错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("rep请求返回onErrorResponse", error.toString());
                Toast.makeText(context, "网络出错", Toast.LENGTH_SHORT).show();
                callback.onError(error);
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", token);
                return headers;
            }
        };

        // 将请求添加到请求队列
        Volley.newRequestQueue(context).add(request);
    }

}
